package top.wilbert.collegelink.forum.controller;

import java.io.*;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import top.wilbert.collegelink.common.enums.TargetTypeEnum;
import top.wilbert.collegelink.common.utils.Query;
import top.wilbert.collegelink.forum.entity.ThumbEntity;
import top.wilbert.collegelink.forum.service.CommentService;
import top.wilbert.collegelink.forum.service.TalkService;
import top.wilbert.collegelink.forum.service.ThumbService;
import top.wilbert.collegelink.common.utils.PageUtils;
import top.wilbert.collegelink.common.utils.R;
import top.wilbert.collegelink.forum.vo.*;


/**
 * @author Augus
 * @email 2531496343@qq.com
 * @date 2023-03-06 19:20:33
 */
@RestController
@RequestMapping("forum/thumb")
public class ThumbController {
    @Autowired
    private ThumbService thumbService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private TalkService talkService;

    /**
     * 点赞/收藏
     *
     * @param thumbVO
     * @return
     */
    @RequestMapping("/save")
    public R save(@RequestBody ThumbVO thumbVO) throws IOException {
        if (thumbService.count(new QueryWrapper<ThumbEntity>().eq("type", thumbVO.getType()).eq("target_id", thumbVO.getTargetId()).eq("target_type", thumbVO.getTargetType()).eq("user_id", thumbVO.getUserId())) != 0) {
            return R.error("用户重复点赞/收藏");
        }
        ThumbEntity thumbEntity = new ThumbEntity();
        thumbEntity.setType(thumbVO.getType());
        thumbEntity.setTargetId(thumbVO.getTargetId());
        thumbEntity.setTargetType(thumbVO.getTargetType());
        thumbEntity.setUserId(thumbVO.getUserId());
        Date date = new Date();
        thumbEntity.setCreateTime(date);
        thumbService.save(thumbEntity);

        long toUserId = 0L;
        if (thumbVO.getType() == 0) {
            if (thumbVO.getTargetType() == TargetTypeEnum.TALK.getTargetType()) {
                talkService.addLikeCount(thumbVO.getTargetId());
                toUserId = talkService.selectUserIdByTalkId(thumbVO.getTargetId());
            } else if (thumbVO.getTargetType() == TargetTypeEnum.COMMENT.getTargetType()) {
                commentService.addLikeCount(thumbVO.getTargetId());
            }
        }


        return R.ok();
    }

    /**
     * 取消点赞
     *
     * @param thumbRemoveVo
     * @return
     */
    @RequestMapping("/remove")
    public R remove(@RequestBody ThumbRemoveVo thumbRemoveVo) {
        ThumbEntity thumbEntity = thumbService.getOne(new QueryWrapper<ThumbEntity>().eq("type", thumbRemoveVo.getType()).eq("target_id", thumbRemoveVo.getTargetId()).eq("target_type", thumbRemoveVo.getTargetType()).eq("user_id", thumbRemoveVo.getUserId()));
        if (thumbEntity == null) {
            return R.error("用户重复取消点赞/收藏");
        }
        int targetType = 0;
        //取消点赞，目标点赞数-1
        if (thumbEntity.getType() == 0) {
            targetType = thumbEntity.getTargetType();
            if (targetType == TargetTypeEnum.TALK.getTargetType()) {
                talkService.reduceLikeCount(thumbEntity.getTargetId());
            } else if (targetType == TargetTypeEnum.COMMENT.getTargetType()) {
                commentService.reduceLikeCount(thumbEntity.getTargetId());
            }
        }

        thumbService.removeById(thumbEntity.getThumbId());

        return R.ok();
    }

    /**
     * 批量取消点赞/收藏
     *
     * @param thumbRemoveListVo
     * @return
     */
    @RequestMapping("/removeList")
    public R removeList(@RequestBody ThumbRemoveListVo thumbRemoveListVo) {
        //批量取消点赞，目标点赞数-n
        if (thumbRemoveListVo.getType() == 0) {
            Collection<ThumbEntity> thumbEntities = thumbService.listByIds(Arrays.asList(thumbRemoveListVo.getThumbIds()));
            if (thumbEntities.size() == 0) {
                return R.error("用户重复取消点赞");
            }
            Integer targetType = 0;
            for (ThumbEntity thumbEntity : thumbEntities) {
                targetType = thumbEntity.getTargetType();
                if (targetType == TargetTypeEnum.TALK.getTargetType()) {
                    talkService.reduceLikeCount(thumbEntity.getTargetId());
                } else if (targetType == TargetTypeEnum.COMMENT.getTargetType()) {
                    commentService.reduceLikeCount(thumbEntity.getTargetId());
                }
            }
        }

        thumbService.removeByIds(Arrays.asList(thumbRemoveListVo.getThumbIds()));

        return R.ok();
    }

    /**
     * 判断用户是否点过赞
     * @param targetId
     * @param targetType
     * @param userId
     * @return
     */
    @RequestMapping("/isLike")
    public Boolean isLike(@RequestParam("targetId") Long targetId, @RequestParam("targetType") Integer targetType, @RequestParam("userId") Long userId) {
        return thumbService.isLike(targetId, targetType, userId);
    }

    /**
     * 根据点赞（收藏）类型获取点赞（收藏）列表
     *
     * @param params
     * @param type
     * @param targetType
     * @param userId
     * @return
     */
    @RequestMapping("/listByType")
    public R listByType(@RequestParam Map<String, Object> params, Integer type, Integer targetType, Long userId) {
        List<ThumbEntity> thumbEntities = thumbService.list(new QueryWrapper<ThumbEntity>().eq("type", type).eq("target_type", targetType).eq("user_id", userId));
        ArrayList<Long> targetIds = new ArrayList<>();
        for (ThumbEntity thumbEntity : thumbEntities) {
            targetIds.add(thumbEntity.getTargetId());
        }

        PageUtils page = new PageUtils();
        if (targetType == TargetTypeEnum.TALK.getTargetType()) {
            page = thumbService.listTalkInfo(new Query<TalkResponseVo>().getPage(params), targetIds);
        }

        return R.ok().setData(page);

    }

    /**
     * 列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("forum:thumb:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = thumbService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{thumbId}")
//    @RequiresPermissions("forum:thumb:info")
    public R info(@PathVariable("thumbId") Long thumbId) {
        ThumbEntity thumb = thumbService.getById(thumbId);

        return R.ok().put("thumb", thumb);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("forum:thumb:update")
    public R update(@RequestBody ThumbEntity thumb) {
        thumbService.updateById(thumb);

        return R.ok();
    }


}
